package com.yj.cloudnote.controller;

import com.alibaba.fastjson.JSONObject;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.yj.cloudnote.common.utils.TokenUtil;
import com.yj.cloudnote.model.Page;
import com.yj.cloudnote.model.User;
import com.yj.cloudnote.service.DirService;
import com.yj.cloudnote.service.FilesService;
import com.yj.cloudnote.service.UserService;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: jy
 * @Description:
 * @Date: 10:40 2018/4/8
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private DirService dirService;
    @Autowired
    private FilesService filesService;

    @RequestMapping(value = "/allUser")
    public @ResponseBody List<User> allUser(){
        return userService.getAllUsers();
    }

    @RequestMapping(value = "/selectByPrimaryKey.json")
    public @ResponseBody User selectByPrimaryKey(int userid){
        return userService.selectByPrimaryKey(userid);
    }

    /**
     * @Author: jy
     * @Description: 登陆啊
     * @Date: 13:55 2018/4/10
     */
    @RequestMapping(value = "/login")
    public @ResponseBody Map<String,Object> login (@RequestBody Map<String,String> map) {
        Map<String,Object> result = new HashMap<>();
        User user = userService.selectByUsername(map.get("usr"));
        if (user != null) {
            if (StringUtils.isEmpty(user.getUserid())) {
                result.put("code",4);
                return result;
//            } else if (!user.getPsd().equals(map.get("psd"))) {
            } else if (!BCrypt.checkpw(map.get("psd"),user.getPsd())) {
                result.put("code",4);
                return result;
            }else if (user.getBlocked() != null && user.getBlocked() == 0) {
                result.put("code",8); // 封号
                return result;
            } else {
                result.put("code",0);
                Map<String,Object> poyload = new HashMap<>();
                poyload.put("username",user.getUsername());
                poyload.put("signMillis",System.currentTimeMillis());
                poyload.put("expMillis",((long)poyload.get("signMillis"))+1000*60*60*5); //过期时间[设置五小时
                String jsonPoyload = JSONObject.toJSONString(poyload);
                result.put("accessToken", TokenUtil.createToken(jsonPoyload));
                result.put("username",user.getUsername());
                result.put("uid",user.getUserid());
                return result;
            }
        } else {
            result.put("code",4);
            return result;
        }
    }

    /**
     * @Author: jy
     * @Description: 验证登陆或登陆过期啊
     * @Date: 14:10 2018/4/10
     */
    @RequestMapping(value = "/isLogin")
    public @ResponseBody Map<String,String> isLogin(@RequestBody Map<String,String> params) {
        String accessToken = params.get("access_token");
        Map<String,String> result = new HashMap<>();
        if (accessToken != null) {
            Boolean isLogin = TokenUtil.authToken(accessToken);
            Boolean isOverdue = TokenUtil.isOverdue(accessToken);
            if (isLogin || !isOverdue) {
                result.put("code", "0");
            } else {
                result.put("code","4");
            }
        } else {
            result.put("code","4");
        }
        return result;
    }

    /**
     * @Author: jy
     * @Description: 不完整的不简单注册
     * @Date: 21:22 2018/4/13
     */
    @RequestMapping(value = "/register")
    @ResponseBody
    public Map<String,String> register(@RequestBody Map<String,String> params) {
        Map<String,String> result = new HashMap<>();
        String username = params.get("username");
        String password = params.get("password");
        User user = new User();
        user.setUsername(username);
        user.setPsd(BCrypt.hashpw(password,BCrypt.gensalt()));
        if (userService.selectByUsername(username) != null) {
            result.put("code","69");
        } else {
            userService.insertUser(user);
            result.put("code","0");
        }

        //创建mongoDB目录集合
        DBObject children = new BasicDBObject("dir_id",2)
                .append("label","欢迎使用CN")
                .append("type","file")
                .append("file_id",1);
        BasicDBList childrens = new BasicDBList();
        childrens.add(children);

        DBObject dir = new BasicDBObject("dir_id",1)
                .append("label","介绍")
                .append("type","folder")
                .append("children",childrens);
        BasicDBList dirs = new BasicDBList();
        dirs.add(dir);

        DBObject cn_dir = new BasicDBObject("username",username)
                .append("dirCount",2)
                .append("fileCount",1)
                .append("directory",dirs);

        //创建mongoDB文件集合
//        DBObject file = new BasicDBObject("file_id",1)
//                .append("title","欢迎使用CN")
//                .append("content","没有介绍");
//        BasicDBList files = new BasicDBList();
//        files.add(file);
//        DBObject cn_files = new BasicDBObject("username",username)
//                .append("files",files);
        DBObject cn_files = new BasicDBObject("username",username)
                .append("file_id",1)
                .append("content","hello world!");

        dirService.initDir(cn_dir);
        filesService.initFiles(cn_files);
        return result;
    }

    @RequestMapping(value = "/getUnblockedUsersByPage")
    @ResponseBody
    public Map<String,Object> getUnblockUser(@RequestBody Map<String,String> params) {
        Map<String,Object> result = new HashMap<>();
        int pageNo = Integer.parseInt((String)params.get("pageNo"));
        int pageSize = Integer.parseInt((String)params.get("pageSize"));
        Page page = new Page();
        page.setPageNo(pageNo);
        page.setPageSize(pageSize);
        List<User> users = userService.getUsersByPage(page);
        int total = userService.getUnblockedCount();
        result.put("users",users);
        result.put("total",total);
        return result;
    }

    @RequestMapping(value = "/blockedById")
    @ResponseBody
    public Map<String,Object> blocked(@RequestBody Map<String,String> params) {
        Map<String,Object> result = new HashMap<>();
        int userid = Integer.parseInt((String)params.get("userid"));
        if (userService.userBlocked(userid)) {
            result.put("code","1");
            return result;
        } else {
            result.put("code","0");
            return result;
        }
    }

    @RequestMapping(value = "/getBlockedUsersByPage")
    @ResponseBody
    public Map<String,Object> getBlockedUsers(@RequestBody Map<String,String> params) {
        Map<String,Object> result = new HashMap<>();
        int pageNo = Integer.parseInt((String)params.get("pageNo"));
        int pageSize = Integer.parseInt((String)params.get("pageSize"));
        Page page = new Page();
        page.setPageNo(pageNo);
        page.setPageSize(pageSize);
        List<User> users = userService.getBlockedUsersByPage(page);
        int total = userService.getBlockedCount();
        result.put("users",users);
        result.put("total",total);
        return result;
    }

    @RequestMapping(value = "/unblockedById")
    @ResponseBody
    public Map<String,Object> unblocked(@RequestBody Map<String,String> params) {
        Map<String,Object> result = new HashMap<>();
        int userid = Integer.parseInt((String)params.get("userid"));
        if (userService.userUnblocked(userid)) {
            result.put("code","1");
            return result;
        } else {
            result.put("code","0");
            return result;
        }

    }
}
